import React from 'react';
import {Spin, Card, Button, Table, Popover} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {DATE_FORMAT, TABLE, FIXED_COLUMN_WIDTH, DATETIME_FORMAT, FILES_API} from '../constants';
import {formatDateTime} from '../utils';
import {getDetailList} from './api';
import {injectIntl} from './intl';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import {Link} from 'react-router-dom';
import DropdownMenu from 'Shared/components/DropdownMenu';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const {Description} = DescriptionList;

class DetailPanel extends React.PureComponent {
    state = {
        isFetching: false,
        hasOperat: false,
        data: [],
        queryCondition: {},
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        const detail = {};
        this.props.list.forEach(v => {
            if(v.id === id) {
                detail.vin = v.vin;
                detail.dealerId = v.dealerId;
            }
            return v;
        });
        this.setState({
            queryCondition: Object.assign(this.state.queryCondition, detail),
            hasOperat: true,
            isFetching: true
        });
        const vin = this.state.queryCondition.vin;
        const dealerId = this.state.queryCondition.dealerId;
        const condition = {
            vin,
            dealerId
        };
        getDetailList(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        data: res.data.content,
                    });
                else
                    this.setState(({
                        isFetching: false
                    }));
            });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }

    render() {
        const {formatMessage} = this.props.intl;
        const {details = [], activities = []} = this.state.data;
        const colums = [
            {
                title: formatMessage({
                    id: 'detailPanel.column.code',
                    defaultMessage: '序号'
                }),
                dataIndex: 'code',
                render: (text, record) => record.code ? record.code : '尚未生成'
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.dealer',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerCode',
                render: (text, record) => `(${record.dealerCode})${record.dealerName}`
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.subDealer',
                    defaultMessage: '经销商'
                }),
                dataIndex: 'subDealerCode',
                render: (text, record) => `(${record.subDealerCode})${record.subDealerName}`
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.repairOrder',
                    defaultMessage: '派工单号'
                }),
                dataIndex: 'repairOrder',
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin',
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.salesDate',
                    defaultMessage: '实销日期'
                }),
                dataIndex: 'salesDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.maintainDate',
                    defaultMessage: '保养日期'
                }),
                dataIndex: 'maintainDate',
                render: text => formatDateTime(text, DATE_FORMAT)
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.mileage',
                    defaultMessage: '行驶里程'
                }),
                dataIndex: 'mileage',
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.createTime',
                    defaultMessage: '创建日期'
                }),
                dataIndex: 'createTime',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            }];
        colums.push({
            title: this.props.intl.formatMessage({
                id: 'tablePanel.column.operation',
                defaultMessage: '操作'
            }),
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (text, r) => {
                const menus = [{
                    id: PERMISSION.update,
                    children: (
                        <Link key="update" to={routes.update.format(r.id)}>
                            {this.props.intl.formatMessage({
                                id: 'tablePanel.operation.update',
                                defaultMessage: '编辑'
                            })}
                        </Link>
                    ),
                    hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        });
        const activityColums = [
            {
                title: formatMessage({
                    id: 'detailPanel.column.num',
                    defaultMessage: '序号'
                }),
                dataIndex: 'num'
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.serviceName',
                    defaultMessage: '服务活动名称'
                }),
                dataIndex: 'serviceName'
            },
            {
                title: formatMessage({
                    id: 'detailPanel.column.isUsed',
                    defaultMessage: '是否参加'
                }),
                dataIndex: 'isUsed',
                render: text => text ? formatMessage({
                    id: 'detailPanel.column.isUsedYes',
                    defaultMessage: '是'
                }) : formatMessage({
                    id: 'detailPanel.column.isUsedNo',
                    defaultMessage: '否'
                })
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'detailPanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                render: (text, record) => {
                    const {attachments = []} = record;
                    if(!attachments.length)
                        return '';
                    const fileList = attachments.map(item =>
                        (<Description key={item.fileId}><a icon="download" href={`${FILES_API.files}/${item.fileId}`} size="small">
                            {item.fileName}</a></Description>));
                    return (<Popover trigger="click" content={<DescriptionList col={1} size="large">
                        {fileList}
                    </DescriptionList>}>
                        <a icon="download" size="small">
                            {this.props.intl.formatMessage({
                                id: 'detailPanel.downloadFile',
                                defaultMessage: '下载附件'
                            })}</a>
                    </Popover>);
                }
            }];
        return (
            <div>
                <Spin spinning={this.state.isFetching}>
                    <Card
                        title={formatMessage({
                            id: 'detailPanel.card.common',
                            defaultMessage: '整车保养记录清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            rowKey="id"
                            columns={colums}
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'detailPanel.card.activities',
                            defaultMessage: '技术升级信息'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            rowKey="num"
                            columns={activityColums}
                            pagination={false}
                            dataSource={activities}
                            {...TABLE} />
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{this.props.intl.formatMessage({
                        id: 'detailPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    list: PropTypes.array,
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getList = selectorFactory(['page', 'domainData', 'list', 'data']);
const mapStateToProps = (state, props) => ({
    permissions: getPermissions(state),
    list: getList(state)
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
